package com.yehebl.orm.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置文件监听
 */
public class ConfigListenerUtil {
    public interface IConfigReload {
        void modify(File f);
    }

    private static final Map<String, IConfigReload> configMap = new ConcurrentHashMap<>();
    private static final Map<String, Long> configTimeMap = new HashMap<>();

    private static boolean isRun = false;

    public static void listen(String path, IConfigReload configReload) {
        configMap.put(path, configReload);
        configTimeMap.put(path, 0L);
        if (isRun) {
            return;
        }
        synchronized (ConfigListenerUtil.class) {
            if (!isRun) {
                isRun = true;
                runListener();
            }
        }
    }

    public static void runListener() {
        new Thread(() -> {
            while (true) {
                try {
                    for (Entry<String, IConfigReload> entry : configMap.entrySet()) {
                        String path = entry.getKey();
                        File f = new File(path);
                        if (configTimeMap.get(path) == 0) {
                            configTimeMap.put(path, f.lastModified());
                        }
                        if (configTimeMap.get(path) < f.lastModified()) {
                            configTimeMap.put(path, f.lastModified());
                            entry.getValue().modify(f);
                        }
                    }
                    Thread.sleep(500L);
                } catch (Exception e) {
                    LogUtil.printWarn("监听配置文件出错:" + e.getMessage());
                }
            }
        }).start();
    }


}
